# koroFileHeader at Yungoal acer
# Create: 2021-06-25 10:18:38
# LastEdit: 2021-07-02 12:57:32
"""检查 DNS：
DNS服务器的地址
Sephora内网DNS服务器地址为：10.157.0.1, 10.157.10.49
"""
__author__ = '749B'

import os, sys
BASE_DIR = os.getcwd()
sys.path.append(BASE_DIR)

# pylint: disable = import-error
from azure_client.models import RuncmdCheck, RuncmdTask
from utils.blueking import job_start, job_success, job_fail

from typing import Optional, List, Tuple
_Check = Tuple[bool, str]


class DnsCheck(RuncmdCheck):

    @staticmethod
    def init_argparse_hook(parser):
        dns_option = parser.add_argument_group('DNS Option', 'DNS检查使用的选项')
        dns_option.add_argument('--dns', required=True, help="逗号隔开的DNS地址")
        return

    def parse_linux(self, task: RuncmdTask) -> _Check:
        errors = []
        out_list = self.std_out.strip().splitlines()[0].split('|')
        for i in self.args.dns.split(','):
            if i not in out_list:
                errors.append(i)
        if errors:
            return False, "未设置dns:%s" % '|'.join(errors)
        return True, "OK"        

    def parse_windows(self, task: RuncmdTask) -> _Check:
        return self.parse_linux(task)
        

def main(args: Optional[List[str]] = None) -> None:
    """主函数"""
    check_obj = DnsCheck(args, SCRIPTS_LINUX, SCRIPTS_WINSOWS, CHECK_ITEMS)
    check_obj.run()
    
    if check_obj.fail_count:
        job_fail("不合规的记录数: %s" % check_obj.fail_count)
    job_success()


SCRIPTS_LINUX = """\
awk -v ORS='|' '/^nameserver/ {print $2}' /etc/resolv.conf | sed 's/.$/\\n/'
"""

SCRIPTS_WINSOWS = """\
(Get-DnsClientServerAddress -AddressFamily "IPv4" | %{$_.ServerAddresses}) -join '|'
"""

CHECK_ITEMS = ['dns']

if __name__ == '__main__':

    job_start()

    ###### 可在此处开始编写您的脚本逻辑代码
    ###### iJobs中执行脚本成功和失败的标准只取决于脚本最后一条执行语句的返回值
    ###### 如果返回值为0，则认为此脚本执行成功，如果非0，则认为脚本执行失败

    main()


